package com.shendu.task.bo;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.shendu.task.domain.TaskDoc;
import com.shendu.task.util.DateUtil;

@Component
public class TaskBo {

	@Autowired
	private MongoTemplate mongo;

	public void save(TaskDoc task) {
		mongo.save(task);

	}
	/**
	 * 按照ID获取任务
	 * @param task
	 * @return
	 */
	public TaskDoc getById(String taskId) {
		Criteria criteria = new Criteria();
		criteria.and("taskId").is(taskId);
		Query query = new Query(criteria);
		return mongo.findOne(query, TaskDoc.class);
	}
	public void updateTask(TaskDoc task) {
		Criteria criteria = new Criteria();
		criteria.and("taskId").is(task.getTaskId());
		Query query = new Query(criteria);
		Update update = new Update();
		update.set("task", task.getTask());
		update.set("checked", task.getChecked());
		update.set("sort", task.getSort());
		update.set("startTime", task.getStartTime());
		update.set("endTime", task.getEndTime());
		update.set("status", task.getStatus());
		update.set("lastSaveRuntime", task.getLastSaveRuntime());
		update.set("runTime", task.getRunTime());
		update.set("timeList", task.getTimeList());
		update.set("del", task.getDel());
		mongo.updateFirst(query, update, TaskDoc.class);
	}

	public List<TaskDoc> list(TaskDoc task) {
		Criteria criteria = new Criteria();
		Query query = new Query(criteria);
		if(!StringUtils.isEmpty(task.getUserId())) {
			criteria.and("userId").is(task.getUserId());
		}
		if(task.getChecked()!=null) {
			criteria.and("checked").is(task.getChecked());
		}
		if(task.getCreateDate()==null) {
			task.setCreateDate(DateUtil.formatDate(new Date(), "yyyy-MM-dd"));
		}
		
		criteria.and("createDate").is(task.getCreateDate());
		criteria.and("del").is(0);//查询未删除
		return mongo.find(query, TaskDoc.class);
	}

}
